﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;

using HsTec.Mobile.Green.BLL;
using InfoSoftGlobal;
using System.Drawing;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using System.Configuration;
using System.Reflection;
using System.Web.UI.WebControls;
using HsTec.Mobile.Green.Util;


public partial class Indicators_QuantitativeManage : System.Web.UI.Page
{
    private IndexFormulaBLL bll = new IndexFormulaBLL();
    private ReportAnalysisBLL rabll = new ReportAnalysisBLL();
    private ReportTemplateBLL rtbll = new ReportTemplateBLL();
    protected string sAreaId = String.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((string)Session["Baimasoft_Pers_ID"] == null)
        {
            Response.Redirect("../Logon.aspx");
        }
        sAreaId = (string)Session["Baimasoft_Report"];
        //绑定区域列表框
        lstArea.Attributes.Add("onclick", "FindSelectedItems(this," + txtArea.ClientID + ");");
        //绑定字段列表框
        lstField.Attributes.Add("onclick", "FindSelectedItems(this," + txtField.ClientID + ");");
        lstDouble.Attributes.Add("onclick", "FindSelectedItems(this," + txtDouble.ClientID + ");");
        chkArea.Attributes.Add("onclick", "chkAll(this)");
        chkField.Attributes.Add("onclick", "chkAll(this)");
        try
        {
            Indicator.Text = Request.QueryString["sIndicator"].ToString();
        }
        catch
        {

        }
        GridView1.Attributes.Add("BorderColor", "LightSkyBlue");
        if (ViewState["sortDirection"] == null)
        {
            ViewState["sortDirection"] = " ASC";
        }
        if (ViewState["sortExpression"] == null)
        {
            ViewState["sortExpression"] = String.Empty;
        }
        if (!IsPostBack)
        {
            this.BindlstArea();
            this.BindrblType();
            hidDivLastYears.Visible = false;
            hidDivConfig.Visible = true;
            trDouble.Visible = false;
        }
    }
    /// <summary>
    /// 绑定区域数据
    /// </summary>
    private void BindlstArea()
    {
        lstArea.DataSource = rabll.GetAreaList(sAreaId);
        lstArea.DataTextField = "Name";
        lstArea.DataValueField = "ID";
        lstArea.DataBind();
    }
    private void BindrblType()
    {
        ListItem li1 = new ListItem("数据表", "0");
        rblType.Items.Add(li1);
        if (String.IsNullOrEmpty(sAreaId))
        {
            ListItem li2 = new ListItem("公式", "1");
            rblType.Items.Add(li2);
            ListItem li3 = new ListItem("考核指标", "2");
            rblType.Items.Add(li3);
        }
    }
    private DataView getInfo()
    {
        string sConfig = String.Empty;
        DataView mydv = null;
        string sErr = String.Empty;
        //处理查询的参数
        //1.处理年月信息 注意 同比和环比
        string sStartYears = sltStartYear.Value + sltStartMonth.Value;
        string sEndYears = sltEndYear.Value + sltEndMonth.Value;
        //2.处理地区信息
        string sArea = String.Empty;
        for (int i = 0; i < lstArea.Items.Count; i++)
        {
            if (lstArea.Items[i].Selected == true)
            {
                sArea += sArea == String.Empty ? lstArea.Items[i].Value + "^" + lstArea.Items[i].Text : "," + lstArea.Items[i].Value + "^" + lstArea.Items[i].Text;
            }
        }
        if (String.IsNullOrEmpty(sArea))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择地市信息!');</script>");
            return null;
        }
        //3.处理字段
        string sField = String.Empty;
        for (int i = 0; i < lstField.Items.Count; i++)
        {
            if (lstField.Items[i].Selected == true)
            {
                sField += sField == String.Empty ? lstField.Items[i].Text + "^" + lstField.Items[i].Value : "," + lstField.Items[i].Text + "^" + lstField.Items[i].Value;
            }
        }
        if (String.IsNullOrEmpty(sField))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择字段信息!');</script>");
            return null;
        }
        //4.处理参数
        if (rdMR.Checked)
            sConfig = "0";
        else if (rdTB.Checked)
            sConfig = "1";
        else if (rdHB.Checked)
            sConfig = "2";
        switch (rblType.SelectedValue)
        {
            case "0":        //表示查询表中数据
                string type = bll.GetTableType(ddlTable.SelectedValue.Trim());
                if (type == "0")
                    mydv = bll.QueryTableField(sArea, sStartYears, sEndYears, sField, ddlTable.SelectedValue.Trim(), sConfig, chkTotal.Checked);
                else
                    mydv = bll.QueryMTableField(sArea, sStartYears, sEndYears, sField, ddlTable.SelectedValue.Trim(), sConfig, chkTotal.Checked);
                if (!String.IsNullOrEmpty(ViewState["sortExpression"].ToString()))
                {
                    //try
                    //{
                    //    mydv.Sort = ViewState["sortExpression"].ToString() + ViewState["sortDirection"].ToString();
                    //}
                    //catch
                    //{
                    //}
                    mydv = Util.SortDataView(mydv, ViewState["sortExpression"].ToString(), ViewState["sortDirection"].ToString());
                }
                break;
            case "1":        //表示查询公式中数据
                mydv = bll.QueryFormula(sArea, sStartYears, sEndYears, sField, ddlTable.SelectedValue.Trim(), sConfig, chkTotal.Checked);
                if (!String.IsNullOrEmpty(ViewState["sortExpression"].ToString()))
                {
                    //try
                    //{
                    //    mydv.Sort = ViewState["sortExpression"].ToString() + ViewState["sortDirection"].ToString();
                    //}
                    //catch
                    //{
                    //}
                    mydv = Util.SortDataView(mydv, ViewState["sortExpression"].ToString(), ViewState["sortDirection"].ToString());
                }
                break;
            case "2":        //表示查询考核指标中数据
                string sLastYears = sltLastYears.Value;
                string[] aryList = sField.Split(',');
                List<string> field = new List<string>();
                for (int i = 0; i < aryList.Length; i++)
                {
                    string[] ary = aryList[i].Split('^');
                    string tmp = SQLHelper.ExecuteString("select IF_ID from tb_IndexFormula where IndexName='" + ary[0] + "'");
                    field.Add(tmp);
                }
                string[] aryarea = sArea.Split(',');
                List<string> area = new List<string>();
                for (int i = 0; i < aryarea.Length; i++)
                {
                    string[] ary = aryarea[i].Split('^');
                    area.Add(ary[0]);
                }
                string sAreaID = String.Empty;
                string sIndiID = String.Empty;
                foreach (string indi in field)
                {
                    sIndiID += String.IsNullOrEmpty(sIndiID) ? indi : "," + indi;
                }
                foreach (string id in area)
                {
                    sAreaID += String.IsNullOrEmpty(sAreaID) ? id : "," + id;
                }
                mydv = bll.GetIndicatorListNewArea(sStartYears, sEndYears, sAreaID, sIndiID, "2");
                if (!String.IsNullOrEmpty(ViewState["sortExpression"].ToString()))
                {
                    //try
                    //{
                    //    mydv.Sort = ViewState["sortExpression"].ToString() + ViewState["sortDirection"].ToString();
                    //}
                    //catch
                    //{
                    //}
                    mydv = Util.SortDataView(mydv, ViewState["sortExpression"].ToString(), ViewState["sortDirection"].ToString());
                }
                break;
        }
        return mydv;
    }
    private void BindGridViewData()
    {
        GridView1.DataSource = getInfo();
        GridView1.DataBind();
    }

    protected void btnReport_ServerClick(object sender, EventArgs e)
    {
        CreateFlash();
    }
    private void CreateFlash()
    {
        StringBuilder sbXML = new StringBuilder();
        DataView mydv = getInfo();
        if (mydv.Count == 0)
        {
            FCLiteral.Visible = false;
            return;
        }
        FCLiteral.Visible = true;
        int iColor = 0;
        string flashURL = String.Empty;
        bool flag = false;
        switch (brlGraphic.SelectedValue)
        {
            case "1":
                flashURL = "../FusionCharts/FCF_MSColumn2D.swf";
                break;
            case "2":
                flashURL = "../FusionCharts/FCF_MSLine.swf";
                break;
            case "3":
                if (mydv.Count == 1)
                {
                    sbXML.Append("<graph showNames='1' decimalPrecision='0'>");
                    for (int i = 0; i < lstField.Items.Count; i++)
                    {
                        if (lstField.Items[i].Selected == true)
                        {
                            sbXML.Append("<set name='" + lstField.Items[i].Text + "' value='" + mydv[0][lstField.Items[i].Text].ToString().Replace("%", "") + "' />");
                        }
                    }
                    sbXML.Append("</graph>");
                    FCLiteral.Text = FusionCharts.RenderChart("../FusionCharts/FCF_Pie2D.swf", "", sbXML.ToString(), "FactorySum", "750", "550", false, false);
                    Text_Confirm_State.Visible = false;
                }
                else
                {
                    Text_Confirm_State.Visible = true;
                    Text_Confirm_State.Text = "含有多条记录无法生成饼图！";
                }
                return;
            case "4":
                flashURL = "../FusionCharts/FCF_MSColumn2DLineDY.swf";
                break;
        }
        switch (DDLx.SelectedValue.Trim())
        {
            case "地区":
                if (brlGraphic.SelectedValue != "4")
                {
                    if (!chkTotal.Checked && int.Parse(sltStartYear.Value + sltStartMonth.Value) != int.Parse(sltEndYear.Value + sltEndMonth.Value))
                    {
                        Text_Confirm_State.Visible = true;
                        Text_Confirm_State.Text = "请选择某一个月份或选中累计复选框来生成图表！";
                        FCLiteral.Visible = false;
                        break;
                    }
                    //生成FLASH图表
                    sbXML.Append("<graph xaxisname='地区' yaxisname='数值' hovercapbg='DEDEBE' hovercapborder='889E6D' rotateNames='0' yAxisMaxValue='100' numdivlines='9' divLineColor='CCCCCC' divLineAlpha='80' decimalPrecision='0' showAlternateHGridColor='1' AlternateHGridAlpha='30' AlternateHGridColor='CCCCCC' caption='报表名称' subcaption='子报表名称'>");
                    sbXML.Append("<categories font='Arial' fontSize='12' fontColor='000000'>");
                    //生成每个柱的信息
                    for (int i = 0; i < lstArea.Items.Count; i++)
                    {
                        if (lstArea.Items[i].Selected == true)
                        {
                            sbXML.Append("<category name='" + lstArea.Items[i].Text + "' />");
                        }
                    }
                    sbXML.Append("</categories>");
                    iColor = 0;
                    for (int i = 0; i < lstField.Items.Count; i++)
                    {
                        if (lstField.Items[i].Selected == true)
                        {
                            iColor++;
                            sbXML.Append("<dataset seriesname='" + lstField.Items[i].Text + "' color='" + this.GetColor(iColor).ToArgb() + "'>");
                            for (int j = 0; j < mydv.Count; j++)
                            {
                                sbXML.Append("<set value='" + mydv[j][lstField.Items[i].Text].ToString().Replace("%", "") + "' />");
                            }
                            sbXML.Append("</dataset>");
                        }
                    }
                    sbXML.Append("</graph>");
                    FCLiteral.Text = FusionCharts.RenderChart(flashURL, "", sbXML.ToString(), "FactorySum", "750", "550", false, false);
                    Text_Confirm_State.Visible = false;
                }
                else
                {
                    if (!chkTotal.Checked && int.Parse(sltStartYear.Value + sltStartMonth.Value) != int.Parse(sltEndYear.Value + sltEndMonth.Value))
                    {
                        Text_Confirm_State.Visible = true;
                        Text_Confirm_State.Text = "请选择某一个月份或选中累计复选框来生成图表！";
                        FCLiteral.Visible = false;
                        break;
                    }
                    //生成FLASH图表
                    sbXML.Append("<graph xaxisname='地区' yaxisname='数值' hovercapbg='DEDEBE' hovercapborder='889E6D' rotateNames='0' yAxisMaxValue='100' numdivlines='9' divLineColor='CCCCCC' divLineAlpha='80' decimalPrecision='0' showAlternateHGridColor='1' AlternateHGridAlpha='30' AlternateHGridColor='CCCCCC' caption='报表名称' subcaption='子报表名称'>");
                    sbXML.Append("<categories font='Arial' fontSize='12' fontColor='000000'>");
                    //生成每个柱的信息
                    for (int i = 0; i < lstArea.Items.Count; i++)
                    {
                        if (lstArea.Items[i].Selected == true)
                        {
                            sbXML.Append("<category name='" + lstArea.Items[i].Text + "' />");
                        }
                    }
                    sbXML.Append("</categories>");
                    iColor = 0;
                    for (int i = 0; i < lstDouble.Items.Count; i++)
                    {
                        if (lstDouble.Items[i].Selected == true)
                        {
                            iColor++;
                            sbXML.Append("<dataset seriesname='" + lstDouble.Items[i].Text + "' color='" + this.GetColor(iColor).ToArgb() + "'>");
                            for (int j = 0; j < mydv.Count; j++)
                            {
                                sbXML.Append("<set value='" + mydv[j][lstDouble.Items[i].Text].ToString().Replace("%", "") + "' />");
                            }
                            sbXML.Append("</dataset>");
                        }
                        else
                        {
                            iColor++;
                            sbXML.Append("<dataset seriesname='" + lstDouble.Items[i].Text + "' color='" + this.GetColor(iColor).ToArgb() + "' parentYAxis='S'>");
                            for (int j = 0; j < mydv.Count; j++)
                            {
                                sbXML.Append("<set value='" + mydv[j][lstDouble.Items[i].Text].ToString().Replace("%", "") + "' />");
                            }
                            sbXML.Append("</dataset>");
                        }
                    }
                    sbXML.Append("</graph>");
                    FCLiteral.Text = FusionCharts.RenderChart(flashURL, "", sbXML.ToString(), "FactorySum", "750", "550", false, false);
                    Text_Confirm_State.Visible = false;
                }
                break;
            case "年月":
                if (brlGraphic.SelectedValue != "4")
                {
                    string sArea = String.Empty;
                    int iNum = 0;
                    for (int i = 0; i < lstArea.Items.Count; i++)
                    {
                        if (lstArea.Items[i].Selected == true)
                        {
                            if (iNum > 1)
                                break;
                            iNum++;

                        }
                    }
                    if (!chkTotal.Checked && iNum > 1)
                    {
                        Text_Confirm_State.Visible = true;
                        Text_Confirm_State.Text = "请选择某一个地区或选中累计复选框来生成图表！";
                        FCLiteral.Visible = false;
                        break;
                    }
                    //生成FLASH图表
                    sbXML.Append("<graph xaxisname='年月' yaxisname='数值' hovercapbg='DEDEBE' hovercapborder='889E6D' rotateNames='0' yAxisMaxValue='100' numdivlines='9' divLineColor='CCCCCC' divLineAlpha='80' decimalPrecision='0' showAlternateHGridColor='1' AlternateHGridAlpha='30' AlternateHGridColor='CCCCCC' caption='报表名称' subcaption='子报表名称'>");
                    sbXML.Append("<categories font='Arial' fontSize='12' fontColor='000000'>");
                    //生成每个柱的信息
                    if (!chkTotal.Checked)
                    {
                        DateTime dStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01");
                        DateTime dEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01");
                        for (DateTime datetime = dStartYears; datetime <= dEndYears; )
                        {
                            sbXML.Append("<category name='" + datetime.ToString("yyyyMM") + "' />");
                            datetime = datetime.AddMonths(1);
                        }
                        if (rdTB.Checked)
                        {
                            DateTime dLastStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddYears(-1);
                            DateTime dLastEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01").AddYears(-1);
                            for (DateTime datetime = dLastStartYears; datetime <= dLastEndYears; )
                            {
                                sbXML.Append("<category name='" + datetime.ToString("yyyyMM") + "' />");
                                datetime = datetime.AddMonths(1);
                            }
                        }
                        if (rdHB.Checked)
                        {
                            DateTime dLastStartMonth = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddMonths(-1);
                            sbXML.Append("<category name='" + dLastStartMonth.ToString("yyyyMM") + "' />");
                        }
                        sbXML.Append("</categories>");
                    }
                    else
                    {
                        DateTime dStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01");
                        DateTime dEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01");
                        if (rdTB.Checked)
                        {
                            DateTime dLastStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddYears(-1);
                            DateTime dLastEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01").AddYears(-1);
                            sbXML.Append("<category name='" + dLastStartYears.ToString("yyyyMM") + "至" + dLastEndYears.ToString("yyyyMM") + "' />");
                        }
                        if (rdHB.Checked)
                        {
                            DateTime dLastStartMonth = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddMonths(-1);
                            DateTime dLastEndMonth = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01").AddMonths(-1);
                            sbXML.Append("<category name='" + dLastStartMonth.ToString("yyyyMM") + "至" + dLastEndMonth.ToString("yyyyMM") + "' />");
                        }
                        sbXML.Append("<category name='" + dStartYears.ToString("yyyyMM") + "至" + dEndYears.ToString("yyyyMM") + "' />");
                        sbXML.Append("</categories>");
                    }
                    iColor = 0;
                    for (int i = 0; i < lstField.Items.Count; i++)
                    {
                        if (lstField.Items[i].Selected == true)
                        {
                            iColor++;
                            sbXML.Append("<dataset seriesname='" + lstField.Items[i].Text + "' color='" + this.GetColor(iColor).ToArgb() + "'>");
                            for (int j = 0; j < mydv.Count; j++)
                            {
                                sbXML.Append("<set value='" + mydv[j][lstField.Items[i].Text].ToString().Replace("%", "") + "' />");
                            }
                            sbXML.Append("</dataset>");
                        }
                    }
                    sbXML.Append("</graph>");
                    FCLiteral.Text = FusionCharts.RenderChart(flashURL, "", sbXML.ToString(), "FactorySum", "750", "550", false, false);
                    Text_Confirm_State.Visible = false;
                }
                else
                {
                    string sArea = String.Empty;
                    int iNum = 0;
                    for (int i = 0; i < lstArea.Items.Count; i++)
                    {
                        if (lstArea.Items[i].Selected == true)
                        {
                            if (iNum > 1)
                                break;
                            iNum++;

                        }
                    }
                    if (!chkTotal.Checked && iNum > 1)
                    {
                        Text_Confirm_State.Visible = true;
                        Text_Confirm_State.Text = "请选择某一个地区或选中累计复选框来生成图表！";
                        FCLiteral.Visible = false;
                        break;
                    }
                    //生成FLASH图表
                    sbXML.Append("<graph xaxisname='年月' yaxisname='数值' hovercapbg='DEDEBE' hovercapborder='889E6D' rotateNames='0' yAxisMaxValue='100' numdivlines='9' divLineColor='CCCCCC' divLineAlpha='80' decimalPrecision='0' showAlternateHGridColor='1' AlternateHGridAlpha='30' AlternateHGridColor='CCCCCC' caption='报表名称' subcaption='子报表名称'>");
                    sbXML.Append("<categories font='Arial' fontSize='12' fontColor='000000'>");
                    //生成每个柱的信息
                    if (!chkTotal.Checked)
                    {
                        DateTime dStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01");
                        DateTime dEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01");
                        for (DateTime datetime = dStartYears; datetime <= dEndYears; )
                        {
                            sbXML.Append("<category name='" + datetime.ToString("yyyyMM") + "' />");
                            datetime = datetime.AddMonths(1);
                        }
                        if (rdTB.Checked)
                        {
                            DateTime dLastStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddYears(-1);
                            DateTime dLastEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01").AddYears(-1);
                            for (DateTime datetime = dLastStartYears; datetime <= dLastEndYears; )
                            {
                                sbXML.Append("<category name='" + datetime.ToString("yyyyMM") + "' />");
                                datetime = datetime.AddMonths(1);
                            }
                        }
                        if (rdHB.Checked)
                        {
                            DateTime dLastStartMonth = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddMonths(-1);
                            sbXML.Append("<category name='" + dLastStartMonth.ToString("yyyyMM") + "' />");
                        }
                        sbXML.Append("</categories>");
                    }
                    else
                    {
                        DateTime dStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01");
                        DateTime dEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01");
                        if (rdTB.Checked)
                        {
                            DateTime dLastStartYears = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddYears(-1);
                            DateTime dLastEndYears = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01").AddYears(-1);
                            sbXML.Append("<category name='" + dLastStartYears.ToString("yyyyMM") + "至" + dLastEndYears.ToString("yyyyMM") + "' />");
                        }
                        if (rdHB.Checked)
                        {
                            DateTime dLastStartMonth = DateTime.Parse(sltStartYear.Value + "-" + sltStartMonth.Value + "-01").AddMonths(-1);
                            DateTime dLastEndMonth = DateTime.Parse(sltEndYear.Value + "-" + sltEndMonth.Value + "-01").AddMonths(-1);
                            sbXML.Append("<category name='" + dLastStartMonth.ToString("yyyyMM") + "至" + dLastEndMonth.ToString("yyyyMM") + "' />");
                        }
                        sbXML.Append("<category name='" + dStartYears.ToString("yyyyMM") + "至" + dEndYears.ToString("yyyyMM") + "' />");
                        sbXML.Append("</categories>");
                    }
                    iColor = 0;
                    for (int i = 0; i < lstDouble.Items.Count; i++)
                    {
                        if (lstDouble.Items[i].Selected == true)
                        {
                            iColor++;
                            sbXML.Append("<dataset seriesname='" + lstDouble.Items[i].Text + "' color='" + this.GetColor(iColor).ToArgb() + "'>");
                            for (int j = 0; j < mydv.Count; j++)
                            {
                                sbXML.Append("<set value='" + mydv[j][lstDouble.Items[i].Text].ToString().Replace("%", "") + "' />");
                            }
                            sbXML.Append("</dataset>");
                        }
                        else
                        {
                            iColor++;
                            sbXML.Append("<dataset seriesname='" + lstDouble.Items[i].Text + "' color='" + this.GetColor(iColor).ToArgb() + "' parentYAxis='S'>");
                            for (int j = 0; j < mydv.Count; j++)
                            {
                                sbXML.Append("<set value='" + mydv[j][lstDouble.Items[i].Text].ToString().Replace("%", "") + "' />");
                            }
                            sbXML.Append("</dataset>");
                        }
                    }
                    sbXML.Append("</graph>");
                    FCLiteral.Text = FusionCharts.RenderChart(flashURL, "", sbXML.ToString(), "FactorySum", "750", "550", false, false);
                    Text_Confirm_State.Visible = false;
                }
                break;
        }
    }

    protected void btnQuery_Click(object sender, EventArgs e)
    {
        BindGridViewData();
    }
    protected void btnExport_ServerClick(object sender, EventArgs e)
    {
        CreateExcel("标题", "Report" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls", "报表");
    }

    private void CreateExcel(string title, string fileName, string sheetNames)
    {
        //待生成的文件名称
        string FileName = fileName;
        string FilePath = Server.MapPath("Excel\\") + FileName;

        FileInfo fi = new FileInfo(FilePath);
        if (fi.Exists)     //判断文件是否已经存在,如果存在就删除!
        {
            fi.Delete();
        }
        if (sheetNames != null && sheetNames != "")
        {
            Excel.Application m_Excel = new Excel.Application();//创建一个Excel对象(同时启动EXCEL.EXE进程) 
            m_Excel.SheetsInNewWorkbook = 1;//工作表的个数 
            Excel._Workbook m_Book = (Excel._Workbook)(m_Excel.Workbooks.Add(Missing.Value));//添加新工作簿 
            Excel._Worksheet m_Sheet = (Excel.Worksheet)m_Book.Sheets[1];
            DataView mydv = getInfo();

            if (mydv == null || mydv.Count <= 0)
                return;
            DataTableToSheet(title, mydv.Table, m_Sheet, m_Book, 1);
            m_Book.SaveAs(FilePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            m_Book.Close(false, Missing.Value, Missing.Value);
            m_Excel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_Book);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(m_Excel);
            m_Book = null;
            m_Sheet = null;
            m_Excel = null;
            GC.Collect();
        }
        Text_Confirm_State.Visible = true;
        Text_Confirm_State.Text = "图表生成成功！<a href='EXCEL\\" + FileName + "'>点击下载</a>";
    }
    /// <summary>
    /// 将DataTable中的数据写到Excel的指定Sheet中
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="m_Sheet"></param>
    public void DataTableToSheet(string title, DataTable dt, Excel._Worksheet m_Sheet, Excel._Workbook m_Book, int startrow)
    {
        //以下是填写EXCEL中数据
        Excel.Range range = m_Sheet.get_Range(m_Sheet.Cells[1, 1], m_Sheet.Cells[1, dt.Columns.Count]);
        range.MergeCells = true;  //合并单元格
        range.Font.Bold = true;   //加粗单元格内字符
        //写入题目
        m_Sheet.Cells[startrow, startrow] = title;
        int rownum = dt.Rows.Count;//行数
        int columnnum = dt.Columns.Count;//列数
        int colum = columnnum + 1;  //获取最大的列数
        int num = rownum + 2;   //得到数据中的最大行数


        //写入列标题
        for (int j = 0; j < columnnum; j++)
        {
            int bt_startrow = startrow + 1;
            //将字段名写入文档
            m_Sheet.Cells[bt_startrow, 1 + j] = dt.Columns[j].ColumnName;
            //单元格内背景色
            m_Sheet.get_Range(m_Sheet.Cells[bt_startrow, 1 + j], m_Sheet.Cells[bt_startrow, 1 + j]).Interior.ColorIndex = 15;
        }
        //逐行写入数据 
        for (int i = 0; i < rownum; i++)
        {
            for (int j = 0; j < columnnum; j++)
            {
                m_Sheet.Cells[startrow + 2 + i, 1 + j] = dt.Rows[i][j].ToString();
            }
        }
        m_Sheet.Columns.AutoFit();
        //在当前工作表中根据数据生成图表
        CreateChart(m_Book, m_Sheet, num, colum);
    }

    private void CreateChart(Excel._Workbook m_Book, Excel._Worksheet m_Sheet, int num, int colum)
    {
        Excel.Chart xlChart = (Excel.Chart)m_Book.Charts.Add(Type.Missing, m_Sheet, Type.Missing, Type.Missing);
        char columName = (char)((short)'A' + colum - 2);
        Excel.Range cellRange = (Excel.Range)m_Sheet.get_Range("A2", columName.ToString() + num.ToString());
        xlChart.ChartWizard(cellRange, Excel.XlChartType.xl3DColumn, Type.Missing, Excel.XlRowCol.xlColumns, 2, 1, true, "", "月份", "数据值", "");
        //Excel.Range oResizeRange;
        //Excel.Series oSeries;

        //m_Book.Charts.Add(Missing.Value, Missing.Value, 1, Missing.Value);
        //m_Book.ActiveChart.ChartType = Excel.XlChartType.xlColumnStacked;//设置图形

        ////
        //char columName = (char)((short)'A' + colum);
        ////设置数据取值范围
        //m_Book.ActiveChart.SetSourceData(m_Sheet.get_Range("A2", columName.ToString() + num.ToString()), Excel.XlRowCol.xlColumns);


        ////m_Book.ActiveChart.Location(Excel.XlChartLocation.xlLocationAutomatic, title);
        ////以下是给图表放在指定位置
        //m_Book.ActiveChart.Location(Excel.XlChartLocation.xlLocationAsObject, m_Sheet.Name);
        //oResizeRange = (Excel.Range)m_Sheet.Rows.get_Item(10, Missing.Value);
        //m_Sheet.Shapes.Item("Chart 1").Top = (float)(double)oResizeRange.Top;  //调图表的位置上边距
        //oResizeRange = (Excel.Range)m_Sheet.Columns.get_Item(6, Missing.Value);  //调图表的位置左边距
        //// m_Sheet.Shapes.Item("Chart 1").Left = (float)(double)oResizeRange.Left;
        //m_Sheet.Shapes.Item("Chart 1").Width = 400;   //调图表的宽度
        //m_Sheet.Shapes.Item("Chart 1").Height = 250;  //调图表的高度

        //m_Book.ActiveChart.PlotArea.Interior.ColorIndex = 19;  //设置绘图区的背景色 
        //m_Book.ActiveChart.PlotArea.Border.LineStyle = Excel.XlLineStyle.xlLineStyleNone;//设置绘图区边框线条
        //m_Book.ActiveChart.PlotArea.Width = 400;   //设置绘图区宽度
        ////m_Book.ActiveChart.ChartArea.Interior.ColorIndex = 10; //设置整个图表的背影颜色
        ////m_Book.ActiveChart.ChartArea.Border.ColorIndex = 8;// 设置整个图表的边框颜色
        //m_Book.ActiveChart.ChartArea.Border.LineStyle = Excel.XlLineStyle.xlLineStyleNone;//设置边框线条
        //m_Book.ActiveChart.HasDataTable = false;


        ////设置Legend图例的位置和格式
        //m_Book.ActiveChart.Legend.Top = 20.00; //具体设置图例的上边距
        //m_Book.ActiveChart.Legend.Left = 60.00;//具体设置图例的左边距
        //m_Book.ActiveChart.Legend.Interior.ColorIndex = Excel.XlColorIndex.xlColorIndexNone;
        //m_Book.ActiveChart.Legend.Width = 150;
        //m_Book.ActiveChart.Legend.Font.Size = 9.5;
        ////m_Book.ActiveChart.Legend.Font.Bold = true;
        //m_Book.ActiveChart.Legend.Font.Name = "宋体";
        ////m_Book.ActiveChart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop;//设置图例的位置
        //m_Book.ActiveChart.Legend.Border.LineStyle = Excel.XlLineStyle.xlLineStyleNone;//设置图例边框线条



        ////设置X轴的显示
        //Excel.Axis xAxis = (Excel.Axis)m_Book.ActiveChart.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary);
        //xAxis.MajorGridlines.Border.LineStyle = Excel.XlLineStyle.xlDot;
        //xAxis.MajorGridlines.Border.ColorIndex = 1;//gridLine横向线条的颜色
        //xAxis.HasTitle = false;
        //xAxis.MinimumScale = 1500;
        //xAxis.MaximumScale = 6000;
        //xAxis.TickLabels.Font.Name = "宋体";
        //xAxis.TickLabels.Font.Size = 9;



        ////设置Y轴的显示
        //Excel.Axis yAxis = (Excel.Axis)m_Book.ActiveChart.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
        //yAxis.TickLabelSpacing = 30;
        //yAxis.TickLabels.NumberFormat = "M月D日";
        //yAxis.TickLabels.Orientation = Excel.XlTickLabelOrientation.xlTickLabelOrientationHorizontal;//Y轴显示的方向,是水平还是垂直等
        //yAxis.TickLabels.Font.Size = 8;
        //yAxis.TickLabels.Font.Name = "宋体";

        ////m_Book.ActiveChart.Floor.Interior.ColorIndex = 8;  
        ///***以下是设置标题*****
        //m_Book.ActiveChart.HasTitle=true;
        //m_Book.ActiveChart.ChartTitle.Text = "净值指数";
        //m_Book.ActiveChart.ChartTitle.Shadow = true;
        //m_Book.ActiveChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;
        //*/

        ////oSeries = (Excel.Series)m_Book.ActiveChart.SeriesCollection(1);
        ////oSeries.Border.ColorIndex = 45;
        ////oSeries.Border.Weight = Excel.XlBorderWeight.xlThick;
        ////oSeries = (Excel.Series)m_Book.ActiveChart.SeriesCollection(2);
        ////oSeries.Border.ColorIndex = 9;
        ////oSeries.Border.Weight = Excel.XlBorderWeight.xlThick;

    }
    protected void cbShowData_CheckedChanged(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {

    }
    protected void GridView1_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
    {
        if (ViewState["sortDirection"].ToString() == " ASC")
        {
            ViewState["sortDirection"] = " DESC";
        }
        else
        {
            ViewState["sortDirection"] = " ASC";
        }
        ViewState["sortExpression"] = e.SortExpression;
        this.BindGridViewData();
        if (!String.IsNullOrEmpty(FCLiteral.Text))
            this.CreateFlash();
    }
    protected void btn_Click(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// 修改查询类型 注意关联下拉框 1:数据表、2;公式、3:考核指标
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rblType_SelectedIndexChanged(object sender, EventArgs e)
    {
        switch (rblType.SelectedValue)
        {
            case "0":           //表示查询表中数据
                ddlTable.Enabled = true;
                sltddlTableBind();
                rdTB.Disabled = false;
                rdHB.Disabled = false;
                rdMR.Disabled = false;
                hidDivLastYears.Visible = false;
                hidDivConfig.Visible = true;
                break;
            case "1":           //表示查询自定义公式项
                ddlTable.Enabled = false;
                rdTB.Disabled = false;
                rdHB.Disabled = false;
                rdMR.Disabled = false;
                sltlstFieldBind(1, null);
                hidDivLastYears.Visible = false;
                hidDivConfig.Visible = true;
                break;
            case "2":           //表示查询考核指标
                ddlTable.Enabled = false;
                rdTB.Disabled = true;
                rdHB.Disabled = true;
                rdMR.Disabled = true;
                sltlstFieldBind(2, null);
                hidDivLastYears.Visible = true;
                hidDivConfig.Visible = false;
                break;
        }
    }
    /// <summary>
    /// 绑定数据表
    /// </summary>
    private void sltddlTableBind()
    {
        ddlTable.DataSource = rtbll.GetBindList("FieldType=0 and FieldTemplate=0");// 
        ddlTable.DataTextField = "FieldAlias";
        ddlTable.DataValueField = "FieldInfo";
        ddlTable.DataBind();
        ddlTable.Items.Insert(0, "请选择...");
        ddlTable.Items[0].Value = "";
    }
    /// <summary>
    /// 绑定字段
    /// </summary>
    /// <param name="iType"></param>
    /// <param name="sTableName"></param>
    private void sltlstFieldBind(int iType, string sTableName)
    {
        switch (iType)
        {
            case 0:
                lstField.DataSource = rtbll.GetList("FieldParent='" + sTableName + "'");
                lstField.DataTextField = "FieldAlias";
                lstField.DataValueField = "FieldName";
                break;
            case 1:
                lstField.DataSource = bll.GetList("FormulaParent<>3");
                lstField.DataTextField = "IndexName";
                lstField.DataValueField = "FormulaSQL";
                break;
            case 2:
                lstField.DataSource = bll.GetList("FormulaParent=3");
                lstField.DataTextField = "IndexName";
                lstField.DataValueField = "FormulaSQL";
                break;
        }
        lstField.DataBind();
    }
    /// <summary>
    /// 数据表下拉框事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlTable_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlTable.SelectedValue.Trim() != "")
            sltlstFieldBind(0, ddlTable.SelectedValue.Trim().Split('|')[0]);
    }
    /// <summary>
    /// 处理颜色
    /// </summary>
    /// <param name="itemIndex"></param>
    /// <returns></returns>
    private Color GetColor(int itemIndex)
    {
        Color objColor = new Color();
        switch (itemIndex)
        {
            case 0:
                objColor = Color.Blue;
                break;
            case 1:
                objColor = Color.DarkOliveGreen;
                break;
            case 2:
                objColor = Color.Red;
                break;
            case 3:
                objColor = Color.Orange;
                break;
            case 4:
                objColor = Color.Purple;
                break;
            case 5:
                objColor = Color.Brown;
                break;
            case 6:
                objColor = Color.Pink;
                break;
            case 7:
                objColor = Color.BurlyWood;
                break;
            case 8:
                objColor = Color.Cornsilk;
                break;
            case 9:
                objColor = Color.Cyan;
                break;
            case 10:
                objColor = Color.DarkCyan;
                break;
            case 11:
                objColor = Color.Chartreuse;
                break;
            case 12:
                objColor = Color.Coral;
                break;
            case 13:
                objColor = Color.Cyan;
                break;
            case 14:
                objColor = Color.Cornsilk;
                break;
            case 15:
                objColor = Color.Chartreuse;
                break;
            case 16:
                objColor = Color.CadetBlue;
                break;
            case 17:
                objColor = Color.Azure;
                break;
            case 18:
                objColor = Color.DarkGray;
                break;
            case 19:
                objColor = Color.DarkMagenta;
                break;
            default:
                objColor = Color.Black;
                break;
        }
        return objColor;
    }

    protected void brlGraphic_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (brlGraphic.SelectedValue == "4")
        {
            lstDouble.Items.Clear();
            trDouble.Visible = true;
            //3.处理字段
            for (int i = 0; i < lstField.Items.Count; i++)
            {
                if (lstField.Items[i].Selected == true)
                {
                    ListItem li = new ListItem(lstField.Items[i].Text, lstField.Items[i].Value);
                    lstDouble.Items.Add(li);
                }
            }
        }
        else
        {
            trDouble.Visible = false;
        }
    }
}